<template>
  <div class="contentBox setScrollbar">
    <div class="setFormMarBtm btnBox">
      <el-form
        :inline="true"
        :model="searchObj"
        class="demo-form-inline"
      >
        <el-form-item label="姓名">
          <el-input
            v-model="searchObj.name"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item
          label="部门"
          prop="deptId"
        >
          <el-cascader
            v-model="searchObj.deptId"
            :options="deptTreeData"
            :props="deptSearchProps"
          />
        </el-form-item>
        <!-- <el-form-item label="登录名">
          <el-input v-model="searchObj.account" placeholder="请输入"></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            @click="onSearch"
          >
            查询
          </el-button>
          <el-button
            type="primary"
            @click="onReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form> <br/>
      <div>
        <el-button
          type="primary"
          @click="addRole"
        >
          新增用户
        </el-button>
        <el-button
          type="primary"
          :loading="importLoading"
          @click="handleUpload"
        >
          导入用户
        </el-button>
        <el-button
          type="primary"
          :loading="exportLoading"
          @click="handledownload"
        >
          导出用户
        </el-button>
        <el-button
          type="primary"
          @click="downloadExcle"
        >
          下载模板
        </el-button>
        <input
          ref="excel-upload-input"
          class="excel-upload-input"
          type="file"
          accept=".xlsx, .xls"
          @change="handleClick"
        >
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column
        prop="name"
        label="姓名"
        min-width="180"
      />
      <el-table-column
        prop="account"
        label="登录名"
        min-width="180"
      />
      <el-table-column
        prop="email"
        label="邮箱"
        min-width="180"
      />
      <el-table-column
        prop="roleName"
        label="角色"
        min-width="120"
      />
      <el-table-column
        prop="deptName"
        label="部门"
        min-width="120"
      />
      <el-table-column
        prop="phone"
        label="手机号"
        width="120"
      />
      <el-table-column
        prop="sex"
        label="性别"
        width="80"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.sex=='M'?'男':scope.row.sex=='F'?'女': null }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="status" label="状态" width="80" align="center">
        <template slot-scope="scope">{{ scope.row.status=='ENABLE'?'启用':'禁用' }}</template>
      </el-table-column>-->
      <el-table-column
        align="center"
        label="操作"
        width="240"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            @click="editUser(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            :disabled="scope.row.userId==1"
            @click="deleteUser(scope.row.userId)"
          >
            删除
          </el-button>
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            :disabled="scope.row.userId==1"
            @click="changeUserState(scope.row)"
          >
            {{ scope.row.status=='ENABLE'?'停用':'启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageBox">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="10"
        layout="prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增用户 -->
    <el-dialog
      title="新增用户"
      :visible.sync="addDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @closed="addHandleClose"
    >
      <el-form
        ref="ruleForm"
        v-loading="addLoading"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 half"
      >
        <el-form-item
          label="登录账号"
          prop="account"
          style="width:45%"
        >
          <el-input
            v-model.trim="ruleForm.account"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          style="width:45%"
        >
          <el-input
            v-model.trim="ruleForm.password"
            type="password"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="姓名"
          prop="name"
          style="width:45%"
        >
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="phone"
          style="width:45%"
        >
          <el-input
            v-model="ruleForm.phone"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
          style="width:45%"
        >
          <el-input
            v-model="ruleForm.email"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="性别"
          style="width:45%"
        >
          <el-select
            v-model="ruleForm.sex"
            placeholder="请选择"
          >
            <el-option
              label="男"
              value="M"
            />
            <el-option
              label="女"
              value="F"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="用户角色"
          prop="roleIds"
          style="width:45%"
        >
          <el-select
            v-model="ruleForm.roleIds"
            value-key="id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleSelectData"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="所在部门"
          prop="deptName"
          style="width:45%"
        >
          <el-cascader
            v-model="ruleForm.deptName"
            :options="deptTreeData"
            :props="deptDeftProps"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item style="width:100%;">
          <div class="formBtnBox">
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              提交
            </el-button>
            <el-button @click="addDialogVisible = false">
              取消
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑用户 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @closed="editHandleClose"
    >
      <el-form
        ref="editRuleForm"
        v-loading="editLoading"
        :model="editRuleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 half"
      >
        <el-form-item
          label="登录账号"
          prop="account"
          style="width:45%"
        >
          <el-input
            v-model.trim="editRuleForm.account"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="密码"
          style="width:45%"
        >
          <el-input
            v-model="editRuleForm.password"
            type="password"
            disabled
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="姓名"
          prop="name"
          style="width:45%"
        >
          <el-input
            v-model="editRuleForm.name"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="phone"
          style="width:45%"
        >
          <el-input
            v-model="editRuleForm.phone"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
          style="width:45%"
        >
          <el-input
            v-model="editRuleForm.email"
            placeholder="请输入"
            @input="change($event)"
          />
        </el-form-item>
        <el-form-item
          label="性别"
          style="width:45%"
        >
          <el-select
            v-model="editRuleForm.sex"
            placeholder="请选择"
          >
            <el-option
              label="男"
              value="M"
            />
            <el-option
              label="女"
              value="F"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="用户角色"
          prop="roleIds"
          style="width:45%"
        >
          <el-select
            v-model="editRuleForm.roleIds"
            value-key="id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleSelectData"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="所在部门"
          prop="deptName"
          style="width:45%"
        >
          <el-cascader
            v-model="editRuleForm.deptName"
            :options="deptTreeData"
            :props="deptDeftProps"
            @change="changeDeptData"
          />
        </el-form-item>
        <el-form-item style="width:100%;">
          <div class="formBtnBox">
            <el-button
              type="primary"
              @click="editSubmitForm('editRuleForm')"
            >
              提交
            </el-button>
            <el-button @click="editDialogVisible = false">
              取消
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      title="删除用户"
      :visible.sync="delDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <p>确认要删除该用户？此操作不可逆</p>
      <div class="formBtnBox">
        <el-button
          type="primary"
          @click="sureDelete"
        >
          确定
        </el-button>
        <el-button @click="delDialogVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
    <!-- 改变状态 -->
    <el-dialog
      :title="userState?'停用用户':'启用用户'"
      :visible.sync="userStateDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <p>确认要{{ userState?'停用':'启用' }}该用户？</p>
      <div class="formBtnBox">
        <el-button
          type="primary"
          @click="sureChange"
        >
          确定
        </el-button>
        <el-button @click="userStateDialogVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { Message } from 'element-ui';
import XLSX from 'xlsx';
import data from '../pdf/content';
export default {
  inject: ['reload'],
  data() {
    // 密码验证
    const validatePassword = (rule, value, callback) => {
      const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/; //8~16位 大小写字母和数字
      // const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,16}/;  //8~16位 大小写字母和数字特殊字符
      const result = re.test(value);
      if (!value) {
        return callback(new Error('请输入密码'));
      } else {
        if (!result) {
          callback(new Error('密码必须包含大小写字母和数字，长度为8~16位'));
        } else {
          callback();
        }
      }
    };
    //账户唯一性校验
    var onlyCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入登录账号'));
      } else {
        // this.$axios
        //   .get(`/system/user/searchNameOrLoginNameIsExisted`, {
        //     params: {
        //       loginName: value
        //     }
        //   })
        //   .then(res => {
        //     if (res.data >= 1) {
        //       callback(new Error("登录账号已存在"));
        //     } else if (res.data == 0) {
        //       callback();
        //     }
        //   });
      }
    };
    // 手机号验证
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
      if (!value) {
        callback();
        // return callback(new Error("电话号码不能为空")); 必填验证  此处非必填
      } else {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error('电话号码格式不正确'));
          }
        }
      }
    };
    // 邮箱验证
    var checkEmail = (rule, value, callback) => {
      const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      const result = emailReg.test(value);
      if (!value) {
        return callback(new Error('请输入邮箱')); //必填验证  此处非必填
      } else {
        if (!result) {
          callback(new Error('邮箱格式不正确'));
        } else {
          callback();
        }
      }
    };
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      delDialogVisible: false,
      userStateDialogVisible: false,
      loading: false,
      addLoading: false,
      editLoading: false,
      downloadLoading: false,
      importLoading: false,
      exportLoading: false,
      autoWidth: true,
      currentPage: 1,
      current: 1,
      total: 0,
      userId: undefined,
      userState: '',
      ruleForm: {},
      editRuleForm: {
        roleIds: {}
      },
      searchObj: {
        name: '',
        deptId: null,
      },
      rules: {
        account: [
          { required: true, message: '请输入登录账号', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: false, validator: checkPhone, trigger: 'blur' }],
        email: [{ required: true, validator: checkEmail, trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }],
        deptName: [{ required: true, message: '请选择部门', trigger: 'change' }]
      },

      tableData: [],
      deptTreeData: [], //部门树数据
      deptData: [], //部门列表数据
      roleData: [], //角色列表所有数据
      roleSelectData: [], //角色下拉列表数据
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      deptDeftProps: {
        children: 'nodes',
        expandTrigger: 'hover',
        emitPath: false,
        label: 'text',
        value: 'text',
        checkStrictly: true
      },
      deptSearchProps: {
        children: 'nodes',
        expandTrigger: 'hover',
        emitPath: false,
        label: 'text',
        value: 'deptId',
        checkStrictly: true
      }
    };
  },
  created() {
    this.getTabTada({ current: 1, limit: 10 });
    this.getDeptTree();
    this.getDeptData();
    this.getRoleData();
    this.getRoleSelect();
  },
  methods: {
    getTabTada(searchObj, pageObj) {
      this.loading = true;
      const pms = Object.assign(searchObj, pageObj);
      console.log('ddddddddddddddddddddd====', pms)
      this.$axios
        .get('/mgr/list', { params: pms })
        .then(res => {
          this.tableData = res.data.records;
          this.loading = false;
          this.total = res.data.total;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onSearch() {
      this.getTabTada(this.searchObj, { current: 1, limit: 10 });
    },
    onReset() {
      this.searchObj = {
        name: '',
        deptId:null
      };
      this.getTabTada({ current: 1, limit: 10 });
    },
    changeDeptData(data){
      console.log('data:', data)
    },
    getDeptTree() {
      //获取部门树 ---> 下拉列表
      this.$axios.get('/dept/treeview').then(res => {
        console.log('ddddddddddd:', res.data)
        this.deptTreeData = res.data;
      });
    },
    getDeptData() {
      //部门列表 ---> 批量导入
      const queryParams = {
        'SYS_DEPT:data[]': {
          '@column': 'dept_id:id,full_name:name'
        }
      };
      this.COM.jsonsqlForSelect(queryParams).then(res => {
        this.deptData = res.data;
      });
    },
    getRoleSelect() {
      //角色列表 ---> 下拉列表
      const queryParams = {
        'SYS_ROLE:data[]': {
          '@column': 'role_id:id,description:description,name:name',
          '@where': {
            'is_open@eq': '1'
          }
        }
      };
      this.COM.jsonsqlForSelect(queryParams).then(res => {
        this.roleSelectData = res.data;
      });
    },
    getRoleData() {
      //角色列表 ---> 批量导入
      this.$axios.get('/role/listRole').then(res => {
        this.roleData = res.data;
      });
    },

    addRole() {
      this.addDialogVisible = true;
    },
    submitForm(formName) {
      // 表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addLoading = true;
          this.$axios
            .post('/mgr/add', this.ruleForm)
            .then(res => {
              if (res.code == 200) {
                this.addDialogVisible = false;
                this.addLoading = false;
                this.getTabTada({ current: this.current, limit: 10 });
                Message.success('新建成功');
              } else {
                console.log(1111);
                this.addLoading = false;
                Message.error(res.message);
              }
            })
            .catch(() => {
              this.addLoading = false;
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    downloadExcle() {
      const queryParams = {
        'c_setting:data{}': {
          '@column': '*',
          '@where': {
            'code@eq': 'user_import_url'
          }
        }
      };
      this.COM.jsonsqlForSelect(queryParams).then(res => {
        window.open(res.data && res.data.data_value, "_self");
      });
    },
    handleUpload() {
      this.$confirm(
        '导入前请确认有本系统提供的Excle模板，点击确定继续导入',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$refs['excel-upload-input'].click();
        })
        .catch(() => {});
    },
    handleClick(e) {
      this.importLoading = true;
      let files = e.target.files;
      let rawFile = files[0]; // only use files[0]
      this.$refs['excel-upload-input'].value = null;
      if (!rawFile) return;
      this.readerData(rawFile)
        .then(({ sheetsData, accountData }) => {
          console.log(sheetsData, accountData);
          // return;
          const queryParams = {
            'sys_user:data[]': {
              '@column': 'account',
              '@where': {
                'account@in': accountData
              }
            }
          };
          this.COM.jsonsqlForSelect(queryParams).then(res => {
            //判断导入数据是否已存在
            if (res.data.length > 0) {
              // this.reload()
              this.importLoading = false;
              let info = '',
                list = res.data;
              JSON.parse(JSON.stringify(res.data)).forEach(item => {
                info = info + item.account + '，';
              });
              this.$alert(
                info.slice(0, -1) + '已存在，请修改Excle数据后重新导入。',
                '提示',
                {
                  confirmButtonText: '确定',
                  callback: action => {}
                }
              );
            } else {
              this.COM.jsonsqlForInsert({
                sys_user: sheetsData
              })
                .then(() => {
                  Message.success('导入成功');
                  this.importLoading = false;
                  // this.reload()
                })
                .catch(() => {
                  this.importLoading = false;
                });
            }
          });
        })
        .catch(data => {
          switch (data) {
          case 1:
            Message.warning('Excle无数据，请输入数据后再次导入');
          case 2:
            Message.warning('Excle数据不完善，请完善数据后再次导入');
          }
          this.importLoading = false;
        });
    },
    readerData(rawFile) {
      //读取excle数据
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsArrayBuffer(rawFile);
        reader.onload = e => {
          let data = e.target.result;
          let workbook = XLSX.read(data, { type: 'array' });
          let firstSheetName = workbook.SheetNames[0];
          let worksheet = workbook.Sheets[firstSheetName];
          let header = this.getHeaderRow(worksheet);
          console.log(XLSX.utils.sheet_to_json(worksheet));
          let results = XLSX.utils.sheet_to_json(worksheet).slice(0, -1);
          if (results.length > 0) {
            // execl有数据
            results = results.map(item => {
              //替换键名
              let random = Number(
                // 生成随机数为用户id
                Math.ceil(Math.random() * 10000000000) +
                  Math.ceil(Math.random() * 10000000000)
              );
              return {
                user_id: random,
                name: item.姓名 && item.姓名.replace(/\s*/g, ''), // 替换空格
                account: item.登录名 && item.登录名.replace(/\s*/g, ''),
                phone: item.手机号 && item.手机号.replace(/\s*/g, ''),
                email: item.邮箱 && item.邮箱.replace(/\s*/g, ''),
                role_id: item.角色 && item.角色.replace(/\s*/g, ''),
                dept_id: item.部门 && item.部门.replace(/\s*/g, ''),
                sex: item.性别 && item.性别.replace(/\s*/g, ''),
                password: 'd732ccb2efbd3564e23bf9b8f94c6d2b',
                salt: 'export',
                status: 'ENABLE'
              };
            });
            console.log(results, 'results222222');
            let flag = true; //数据完善
            for (let key in results) {
              //必填数据检验
              for (let item in results[key]) {
                if (item != 'sex' && item != 'phone') {
                  if (
                    results[key][item] == undefined ||
                    results[key][item] == ''
                  ) {
                    flag = false;
                    break;
                  }
                }
              }
              // if( (results[key].account == undefined || results[key].account == "") ) {}
            }
            if (flag) {
              // console.log("resolve");
              let sheetData = this.resetSheet(
                results,
                this.roleData,
                this.deptData
              );
              resolve(sheetData);
            } else {
              // 2表示数据不完善
              reject(2);
            }
          } else {
            // 1表示无数据
            reject(1);
          }
        };
      });
    },

    resetSheet(sheets, roleList, deptList) {
      //处理读取的数据
      let obj = {},
        sheetsData = [],
        accountData = [];
      sheets = sheets
        .reduce((item, next) => {
          //去重
          obj[next.account]
            ? ''
            : (obj[next.account] = true && item.push(next));
          return item;
        }, [])
        .map(item => {
          if (item.sex == '男') {
            //改变性别
            item.sex = 'M';
          } else {
            item.sex = 'F';
          }
          deptList.map(ele => {
            //改变部门id
            if (item.dept_id == ele.name) {
              item.dept_id = ele.id;
            }
          });
          roleList.map(ele => {
            //改变角色id
            if (item.role_id == ele.name) {
              item.role_id = ele.id;
            }
          });
          sheetsData.push(item);
          accountData.push(item.account);
          return item;
        });
      return { sheetsData, accountData };
    },
    getHeaderRow(sheet) {
      const headers = [];
      const range = XLSX.utils.decode_range(sheet['!ref']);
      let C;
      const R = range.s.r;
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C; // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
        headers.push(hdr);
      }
      return headers;
    },
    handledownload() {
      this.exportLoading = true;
      this.$axios
        .get('/mgr/list')
        .then(res => {
          const list = res.data.map(item => {
            if (item.sex == 'M') {
              item.sex = '男';
            } else {
              item.sex = '女';
            }
            return item;
          });
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = [
              '姓名',
              '登录名',
              '邮箱',
              '角色',
              '部门',
              '手机号',
              '性别'
            ];
            const filterVal = [
              'name',
              'account',
              'email',
              'roleName',
              'deptName',
              'phone',
              'sex'
            ];
            const data = this.formatJson(filterVal, list);
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '用户表',
              autoWidth: this.autoWidth,
              bookType: this.bookType
            });
            this.exportLoading = false;
          });
        })
        .catch(() => {
          this.exportLoading = false;
        });
    },
    formatJson(filterVal, jsonData) {
      console.log(jsonData);
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    editUser(row) {
      this.editRuleForm = JSON.parse(JSON.stringify(row));
      if (
        this.editRuleForm.roleIds &&
        typeof this.editRuleForm.roleIds.id != 'string'
      ) {
        this.editRuleForm.roleIds.id = String(this.editRuleForm.roleIds.id);
      }
      this.editDialogVisible = true;
    },
    editSubmitForm(formName) {
      // 编辑表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.editLoading = true;
          this.$axios
            .post('mgr/edit', this.editRuleForm)
            .then(res => {
              if (res.code == 200) {
                this.getTabTada({ current: this.current, limit: 10 });
                this.editDialogVisible = false;
                this.editLoading = false;
                Message.success('编辑成功');
              } else {
                this.editLoading = false;
                Message.error(res.message);
              }
            })
            .catch(() => {
              this.editLoading = false;
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    deleteUser(id) {
      this.userId = id;
      this.delDialogVisible = true;
    },
    sureDelete() {
      // console.log(this.userId);
      this.$axios
        .get(`mgr/delete?userId=${this.userId}`)
        .then(() => {
          this.delDialogVisible = false;
          Message.success('已删除');
          this.getTabTada({ current: this.current, limit: 10 });
        })
        .catch(() => {
          Message.error('删除失败，请检查网络');
        });
    },
    changeUserState(row) {
      this.userId = row.userId;
      if (row.status == 'ENABLE') {
        this.userState = true; // 用户启用状态
      } else {
        this.userState = false; // 用户停用状态
      }
      this.userStateDialogVisible = true;
    },
    sureChange() {
      if (this.userState) {
        this.$axios
          .get(`mgr/freeze?userId=${this.userId}`)
          .then(() => {
            Message.success('已停用');
            this.getTabTada({ current: this.current, limit: 10 });
            this.userStateDialogVisible = false;
          })
          .catch(() => {
            Message.error('停用失败，请检查网络');
          });
      } else {
        this.$axios
          .get(`mgr/unfreeze?userId=${this.userId}`)
          .then(() => {
            Message.success('已启用');
            this.getTabTada({ current: this.current, limit: 10 });
            this.userStateDialogVisible = false;
          })
          .catch(() => {
            Message.error('启用失败，请检查网络');
          });
      }
    },
    change(e) {
      this.$forceUpdate();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getTabTada({ current: val, limit: 10 });
    },

    addHandleClose() {
      this.$refs.ruleForm.resetFields();
    },
    editHandleClose() {
      this.$refs.editRuleForm.resetFields();
    },
    sureAllotRole() {}
  }
};
</script>
<style lang="scss" scoped>
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.setFormMarBtm {
  display: flex;
  justify-content: space-between;
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
